package register

import (
	"bytes"
	"encoding/json"
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/service-center/constant"
	"gitee.com/zaper/service-center/model"
	"gitee.com/zaper/service-center/os_env"
	"gitee.com/zaper/service-center/util"
	fmkutil "gitee.com/zaper/software-framework/util"
	"os"
	"runtime/debug"
	"time"
)

const (
	dynConfInterface = "/api/v1/nginx/dynconf"
)

func InitializeNginxConf() {
	if model.PortChan == nil {
		model.PortChan = make(chan string)
	}
	port := <-model.PortChan
	// 启动先注册一次，后续再心跳继续
	retry(registerNginx, port, 20)
}

func registerNginx(port string) bool {
	url := fmt.Sprintf("https://%s%s", os.Getenv(os_env.NginxDomainKey), dynConfInterface)
	defer func() {
		e := recover()
		if e != nil {
			logger.Errorf("recover err is %s ,stack is %s", e, debug.Stack())
		}
	}()
	srvConf := &model.ServerConf{
		ServerName: os.Getenv(os_env.ServiceNameKey),
		Line: []model.ServerLine{
			{Ip: fmt.Sprintf("%s:%s", constant.LocalHost, port), Weight: "10"},
		},
	}
	request, err := json.Marshal(srvConf)
	if err != nil {
		logger.Warn("srvConf parse fail, err is %s", err)
		return false
	}
	httpClientManager := fmkutil.NewHttpClientManager()
	resp, err := httpClientManager.Post(url, constant.ContentType, bytes.NewReader(request))
	if err != nil {
		logger.Errorf("request nginx fail, error is %s", err)
		return false
	}
	logger.Info("============== %s", string(resp))
	response := util.HttpResponseError{}
	err = json.Unmarshal(resp, &response)
	if err != nil {
		logger.Warn("Unmarshal Body, err is %s", err)
		return false
	}
	if response.ErrorCode != 0 {
		logger.Warn("register running")
		return false
	}
	logger.Warn("register success")
	return true
}
func retry(function func(string) bool, port string, delay int) bool {
	for {
		if function(port) {
			return true
		} else {
			time.Sleep(time.Duration(delay) * time.Second)
		}
	}
}
